﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using ECCIT.Extension.Weibo_v2.Model;
using ECCIT.Extension.Weibo_v2.Common;
using ECCIT;
using ECCIT.Security;
using ECCIT.Web;
using OgilvyOne.UKNow.BLL;
using OgilvyOne.UKNow.Configuration;
using OgilvyOne.UKNow.Mobile.Model;
using OgilvyOne.UKNow.Mobile.Utilities;
using OgilvyOne.UKNow.Model;
using System.Configuration;
namespace OgilvyOne.UKNow.Mobile.APIs.Avatar
{
  public  class Update:IHttpHandler
    {
        APIComm acm = new APIComm();
        
        public bool IsReusable
        {
            get { return true; }
        }
      
      

        public void ProcessRequest(HttpContext context)
        {

            try
            {
                Stream stream = context.Request.InputStream;
                var memberid = context.Request["uid"];
                var pw = context.Request["pwd"];
                var newpw = context.Request["newpwd"];
                int i = 0;
                int uid = 0;
                int.TryParse(memberid, out uid);
                if (uid > 0)
                {
                    #region
                    MemberBLL mbll = new MemberBLL(2052);
                    MemberModel mm = mbll.getMemberByID(uid);
                    string imagename = mm.MemberImg;
                    var model = new UserImg();
                    model.UserID = uid;
                    model.Avatar = !string.IsNullOrEmpty(mm.MemberImg)
                                       ? ConfigCacheManager.DomainName +
                                         ConfigCacheManager.FilePath.GetFrontImageVirtualPath(imagename)
                                       : "";
                    if (pw != null && newpw != null)//修改密码
                    {
                        if (mbll.CheckPwEqual(pw, uid))
                        {
                            mm.Password = MD5Crypto.GetMD5Hash(newpw);
                            if (mbll.UpdateMemberImg(mm, false))
                            {
                                i = 1;
                            }

                        }
                        else
                        {
                            context.Response.Write(ResultUtility.ReturnResultJson("-5", "", "密码错误"));
                            return;
                        }
                    }
                    if(context.Request.Files["avatar"]!=null)//更新头像
                    {
                        imagename = SaveImage(context);
                        mm.MemberImg = imagename;
                        if(mbll.UpdateMemberImg(mm,true))
                        {

                            i = i==1 ? 3 : 2;
                            model.Avatar =
                                ConfigCacheManager.DomainName +
                                ConfigCacheManager.FilePath.GetFrontImageVirtualPath(imagename);

                        }
                        else
                        {
                            context.Response.Write(ResultUtility.ReturnResultJson("-2", JsonSerializationHelper.ObjectToJson(model), "头像修改失败"));
                        }

                    }
                    string s = JsonSerializationHelper.ObjectToJson(model);
                    switch (i)
                    {
                        case 1: context.Response.Write(ResultUtility.ReturnResultJson("0", s, "密码修改成功"));
                            break;
                        case 2: context.Response.Write(ResultUtility.ReturnResultJson("0", s, "头像修改成功"));
                            break;
                        case 3: context.Response.Write(ResultUtility.ReturnResultJson("0", s, "密码、头像修改成功"));
                            break;
                        default:
                            break;
                    }
                    #endregion
                }
                else
                {
                    context.Response.Write(ResultUtility.ReturnResultJson("-4", "", "参数错误"));
                }

                //int uid = Convert.ToInt32(context.Request.QueryString["uid"].ToString());
                //upmod(uid, context);
            }
            catch (Exception ex)
            {

                context.Response.Write(ResultUtility.ReturnResultJson("0", "", "头像修改失败"+ex.Message));
            }
           

        }
        //private void upmod(int uid,HttpContext htc)
        //{
        //    MemberBLL mbll = new MemberBLL(2052);
        //    MemberModel mm = mbll.getMemberByID(uid);
        //    var imagename = SaveImage(htc);
        //    mm.MemberImg =imagename; //saveImg(stream, htc, path);
        //    var model = new UserImg();
        //    model.UserID = (int)mm.ID;
        //    if(mbll.UpdateMemberImg(mm,true))
        //    {
               
        //        model.Avatar =
                   
        //            ConfigCacheManager.DomainName + ConfigCacheManager.FilePath.GetFrontImageVirtualPath(imagename);
        //        string s = JsonSerializationHelper.ObjectToJson(model);
        //        htc.Response.Write(ResultUtility.ReturnResultJson("0", s, "头像修改成功"));


        //    }
        //    else
        //    {
        //        model.Avatar = !string.IsNullOrEmpty(mm.MemberImg)
        //                           ? ConfigCacheManager.DomainName +
        //                             ConfigCacheManager.FilePath.GetFrontImageVirtualPath(mm.MemberImg)
        //                           : "";
        //        string s = JsonSerializationHelper.ObjectToJson(model);
        //        htc.Response.Write(ResultUtility.ReturnResultJson("0", s, "头像修改失败"));

        //    }



        //   // return  toJson(mm);
        //}

        private string SaveImage(HttpContext context)
        {
            try
            {
                HttpPostedFile file = context.Request.Files["avatar"];
                if (file == null) return string.Empty;

                ResultInfo result = UploadedFile.Save(file, ConfigCacheManager.FilePath.UploadFrontImagePath, UploadedFile.RenameHandlers.RenameToGuid);
                if (result.Result)
                {
                    return ((FileInfo)result.ReturnObject).Name;
                }
                else
                {
                    if (result.Exception != null)
                        throw result.Exception;
                    return null;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("用户头像图片时发生异常。错误信息：" + ex.Message);
            }
        }
        //private string toJson(MemberModel mem)
        //{
        //    Dictionary<string, string> prodir = new Dictionary<string, string>();
        //    prodir.Add("uid", "ID");
          
        //    prodir.Add("avatar", "MemberImg");
        //    return sucjson("0", acm.ObjToJson(mem, prodir), "头像修改成功");


        //}

        //private string sucjson(string errcode, string datastr, string sucMsg)
        //{
        //    string e = "'e':" + errcode;
        //    string d = "'d':" + datastr;
        //    string w = String.Format("'w':'{0}'", sucMsg);
        //    return "{" + String.Format("{0},{1},{2}", e, d, w) + "}";
        //}
        //private string RegisterFaillJson()
        //{
        //    return sucjson("2", "''", "注册失败");
        //}
        //private string saveImg(Stream stream, HttpContext htc, string path)
        //{

        //    long length = stream.Length;
        //    byte[] buffer = new byte[length];
        //    int readCount = stream.Read(buffer, 0, Convert.ToInt32(length));

        //    string imageName = Guid.NewGuid().ToString() + ".jpg";
        //    string vpath = path + imageName;
        //    string fileName = htc.Server.MapPath(vpath);
        //    FileStream pFileStream = null;
        //    try
        //    {
        //        pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);
        //        pFileStream.Write(buffer, 0, readCount);
        //        return imageName;
        //    }
        //    catch (Exception)
        //    {
        //        return null;
        //    }
        //    finally
        //    {
        //        if (pFileStream != null)
        //            pFileStream.Close();
        //    }
        //}
        
       
    }
}
